package com.weike.test.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.weike.test.mapper.BaseMapper;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: DateBaseConnectionFactory
 * @Author: YuanDing
 * @Date: 2025/5/6 20:03
 * @Description:
 * 数据源工厂类
 */

@Data
@Configuration
@ConfigurationProperties("spring.datasource")
public class DateBaseConnectionFactory {

    private String username;

    private String password;

    private String host;

    private String port;



    @Autowired
    private BaseMapper baseMapper;


    public static final Map<String , DataSource> DATA_SOURCE_MAP = new HashMap<>();

    @PostConstruct
    public void init() throws Exception {

        HashMap<String, Object> connectMap = new HashMap<>();
        connectMap.put("username" , username);
        connectMap.put("password" , password);
        connectMap.put("driverClassName", "com.mysql.cj.jdbc.Driver");

        List<String> dataBaseList = baseMapper.selectAllDataBase();

        dataBaseList.forEach(dataBase -> {
            String prefix = "jdbc:mysql://" + host + ":" + port + "/";
            String suffix = "?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true";
            String url = prefix + dataBase + suffix;
            connectMap.put("url" , url);
            try {
                DataSource druidDataSource = DruidDataSourceFactory.createDataSource(connectMap);
                DATA_SOURCE_MAP.put(dataBase , druidDataSource);
            } catch (Exception e) {
                System.err.println("数据库【" + dataBase +  "】连接失败！原因：" + e.toString());
            }

        });
    }

    public static Connection getConnection(String dataBaseName) throws SQLException {
        return DATA_SOURCE_MAP.get(dataBaseName).getConnection();
    }

}
